// packagBuy/pages/marketing/activityPage/activityPage.js
var util = require('../../../../utils/util')   //引入配置公共请求接口
import {
  getAddrCode,
  getParamByScene
} from '../../../../config/config'
var configUrl = require('../../../../config/config') //引入配置接口文件
var util = require('../../../../utils/util')
//获取应用实例
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    windowHeight :400,
    windowWidth:300,
    activityId:'',
    footprintGuid: '', //足迹全局id
    imgUrl: getApp().globalData.imgUrl,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    showJoinActivity:true,
    activityImgs:{},//门店活动
    imgInfo:{
      imageWidth :300,
      imageHeight:300
    },//图片自适应宽高
    imgInfo2:{
      imageWidth :300,
      imageHeight:300
    },//已领取页面
    titleHeight: '',
    /**-合伙人--*/
    isShowPartnerAll: 1,
    showPartnerCodePop: false,
    authorizationPopup: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    app.getLogin((re)=>{ 
      if(!re){
        this.setData({
          authorizationPopup: true
        })
      }
    })
    let that = this
    if (!wx.getStorageSync('loginMsg').token) {
      app.initLogin() //初始化登录
    }
    wx.getSystemInfo({
      success(res) {
        let statusBarHeight = res.statusBarHeight
        let listMargintop = res.statusBarHeight + 65 + 59
        that.setData({
          windowHeight : res.windowHeight,
          windowWidth:res.windowWidth,
          titleHeight: statusBarHeight + 'px',
          listMargintop: listMargintop + 'px'
        })
      }
    })



    let addrCode = wx.getStorageSync('addrCode')

    //有合伙人信息，则分享进入(会话或扫码)
    if (options.scene || options.hid) {
      
      var scene = options.hid ? options.hid : decodeURIComponent(options.scene) //参数二维码传递过来的参数
      //会话进入
      if (options.hid) {
        var stInFun = setInterval(() => {
          if (wx.getStorageSync('getLocation') === 'N') {
            that.setData({
              showSetting: true
            })
          }
          if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
            that.setData({
              showSetting: false
            })
            clearInterval(stInFun)
            if (!wx.getStorageSync('loginMsg').loginState) {
              if (wx.getUserProfile) {
                app.getUserProfile(function(){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                })
              } else {
                if(!wx.getStorageSync('loginMsg').bindingPhone){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                }
              }
              // this.setData({
              //   isShowGetUserInfo: true
              // })
            }
            app.bindingPartner(options.hid)
            that.getShopActivity()
          }
        }, 1000)
      } else {
        //二维码进入
        app.getShareCode(scene, (res) => {
          var stInFun = setInterval(() => {
            if (wx.getStorageSync('getLocation') === 'N') {
              that.setData({
                showSetting: true
              })
            }
            if (wx.getStorageSync('loginMsg').token && wx.getStorageSync('addrCode').provinceCode) {
              that.setData({
                showSetting: false
              })
              clearInterval(stInFun)
              if (!wx.getStorageSync('loginMsg').loginState) {
                if (wx.getUserProfile) {
                  app.getUserProfile(function(){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  })
                } else {
                  if(!wx.getStorageSync('loginMsg').bindingPhone){
                    that.setData({
                      getPhoneNumberData:{
                        isShowGetPhoneNumber:true
                      }
                    })
                  }
                }
              }
              app.bindingPartner(res.userId)
            }else{
              if (wx.getUserProfile) {
                app.getUserProfile(function(){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                })
              } else {
                if(!wx.getStorageSync('loginMsg').bindingPhone){
                  that.setData({
                    getPhoneNumberData:{
                      isShowGetPhoneNumber:true
                    }
                  })
                }
              }
            }
            app.reqFun.requestJson("GET", getParamByScene + options.scene, '', (response) => {
              if (response.data) {
                const res = response.data
                if (res.success == 1 && res.data && res.data.id) {
                  this.getShopActivity()
                  that.getUserLocation((res) => {
                    if (res.getSetting) {
                      that.setData({
                        showSetting: true
                      })
                    }
                  })
                }
              }
            })
          }, 1000)
        })
      }
    } else {
      // 门店活动
      this.getShopActivity()
    }
  },
  // 参加门店活动
  joinShopActivety(){
    app.reqFun.requestJson('post',configUrl.joinShopActivity,{},(res)=>{
      console.log('参加活动res',res)
      if(res.data.success){
        this.setData({
          showJoinActivity:false
        })
      }else{
        wx.showToast({ title: res.data.msg, icon: 'none' });
      }
    })
   
  },
  getShopActivity(){
    app.reqFun.requestJson('get',configUrl.getShopActivity,{},(res)=>{
      console.log('门店活动图片',res)
      if(res.data.success){
        this.setData({
          activityImgs:res.data.data
        })
      }else{
        wx.showToast({ title: res.data.msg, icon: 'none' });
        setTimeout(()=>{
        wx.navigateBack({
                 delta: 1
               })
        },1500)
       
      }
    })
   
  },
  bindGetUserInfo: function (e) { //登录-注册
    var that=this;
    app.getUserInfo()
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
    var setFun=setInterval(()=>{
      if(wx.getStorageSync('showGetPhone')){
        that.setData({
          getPhoneNumberData:{
            isShowGetPhoneNumber:true,
          },
          showSetting: false,
          isShowGetUserInfo: false
        })
        wx.removeStorageSync('showGetPhone')
        clearInterval(setFun)
      }
    },1000)

  },
  onCloseShowGetUserInfo() { //关闭弹出层
    this.setData({
      showSetting: false,
      isShowGetUserInfo: false
    })
  },
   /**绑定手机号 ---str*/
   closeGetphone(){
    this.setData({
      getPhoneNumberData:{
        isShowGetPhoneNumber:false

      }
    })
  },
  getPhoneNumber(e){
    var that=this;
    let loginMsg = wx.getStorageSync('loginMsg')
    if (e.detail.iv && e.detail.encryptedData) {
      let option = {}
      option.encryptedData = e.detail.encryptedData
      option.iv = e.detail.iv
      option.openid = loginMsg.openid
      option.session_key = loginMsg.session_key
      app.reqFun.requestJson('POST',configUrl.decryptGetPhone,option,(res)=>{
        if(res.data.success==1){
          that.setData({
            getPhoneNumberData:{
              isShowGetPhoneNumber:false,
            }
          })
          wx.showToast({
            title: '绑定成功。',
          })
        }
      })
    } else {
      // console.log('取消')
    }
  },
  //获取用户地理位置
  getUserLocation: function (callback) {
    let that = this
    // console.log('活动页定位')
    if (wx.getStorageSync('getLocation')) {
      // console.log('首页等待appJs定位完成')
      var setGetLocation=setInterval(()=> {
        if (!wx.getStorageSync('getLocation')) {
          callback({
            'showSetting':true,
            'getSetting':true
          })
          clearInterval(setGetLocation)
        }
        if (wx.getStorageSync('locationInfo')) {
          let res = wx.getStorageSync('locationInfo')
          const latitude = res.latitude
          const longitude = res.longitude
          var laorln = util.qqMapTransBMap(latitude, longitude)
          wx.setStorageSync('latAndLong', laorln)
          var parms = {
            latitude: laorln.latitude,
            longitude: laorln.longitude
          }
          app.reqFun.requestJson('get', getAddrCode, parms, (res) => {
            if (res.data.success == 1) {
              that.getShopActivity()
            }
          })
          clearInterval(setGetLocation)
        }
      },1000)
      return
    }
    wx.getSetting({
      success(res) {
        if (res.authSetting['scope.userLocation'] != false) {
          wx.getLocation({
            type: 'wgs84',
            success(res) {
              const latitude = res.latitude
              const longitude = res.longitude
              var laorln = util.qqMapTransBMap(latitude, longitude)
              wx.setStorageSync('latAndLong', laorln)
              var parms = {
                latitude: laorln.latitude,
                longitude: laorln.longitude
              }
              app.reqFun.requestJson('get', getAddrCode, parms, (res) => {
                if (res.data.success == 1) {
                  that.getShopActivity()
                }
              })
            }
          })
        } else {
          callback({
            'showSetting': true,
            'getSetting': true
          })
        }
      }
    })
  },
  goBack() {
    wx.navigateBack({
      delta: -1
    })
  },
  toBack() {
    wx.navigateBack({
      url: '/packagBuy/pages/marketing/poster/index/index',
    })
  },
  goIndex() { //进入首页
    wx.navigateTo({
      url: '/pages/newIndex/newIndex',
    })
  },
  goEvaluate() { //进入个人中心
    wx.navigateTo({
      url: '/packagMy/pages/personal/index/index',
    })
  },
  gotoCarbuy(e) { //进入购物车
    wx.reLaunch({
      url: '/packagBuy/pages/carbuy/carbuy',
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      footprintGuid: util.guid()
    })
    setTimeout(()=>{
      this.setData({
        partnerInfo:getApp().globalData.partnerInfo
      })
      },500)
    if (this.data.activityId) {
      //保存访问足迹
      app.saveAccessFootprint(this.data.footprintGuid, 'activityPage', this.data.activityId)
    } else {
      //拿到资源id再记录足迹
      var footprintWaitResourceIdTimer = setInterval(()=>{
        if(this.data.activityId){
          //保存访问足迹
          app.saveAccessFootprint(this.data.footprintGuid, 'activityPage', this.data.activityId)
          clearInterval(footprintWaitResourceIdTimer)
        }
      }, 100)
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    //保存退出足迹
    app.saveQuitFootprint(this.data.footprintGuid)
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },
  goreBack(e) {
    wx.navigateBack({
      delta: 1,
    })
  },
  goHome: function (e) { //返回主页
    wx.reLaunch({
      url: '/pages/newIndex/newIndex'
    })
  },
  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: '活动页',
      desc: '活动页',
      path: `/packagBuy/pages/marketing/shopActivity/shopActivity?hid=${wx.getStorageSync('loginMsg').userId}`
    }
  },
  //展开合伙人信息
  showPartnerAll: function () {
    let isShowPartnerAll;
    if (this.data.isShowPartnerAll == 1) {
      isShowPartnerAll = 0;
    } else {
      isShowPartnerAll = 1;
    }
    this.setData({
      isShowPartnerAll: isShowPartnerAll,
    })
  },
  //展示合伙人二维码
  partnerCode: function (e) {
    // this.setData({
    //   showPartnerCodePop: true,
    // })
    let codeImg=e.target.dataset.url
    wx.previewImage({
      urls:[codeImg],
      current: codeImg, // 当前显示图片的http链接
     })
  },
  //关闭合伙人二维码
  closeCodePop: function () {
    // console.log("3253456678dsgudkdkgfksfvkjdsvbjkdsvbvkj")
    this.setData({
      showPartnerCodePop: false,
    })
  },
  //拨打合伙人电话
  partnerPhone: function () {
    let that = this;
    wx.makePhoneCall({
      phoneNumber: that.data.partnerInfo.partnerPhone,
    })
  }
})
